package com.px.gis.controller;


import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.px.gis.entity.Area;
import com.px.gis.service.IAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController()
@RequestMapping("area")
public class AreaController {

    @Autowired
    private IAreaService areaService;

    @GetMapping("search")
    public String get(@RequestParam("point") List<String> points) {
        JSONObject result = new JSONObject();
        result.set("code", 200);
        if (2 == points.size()) {
            // 传入对角点
            List<String> rightUp = Arrays.stream(points.get(0).split(",")).collect(Collectors.toList());
            List<String> leftDown = Arrays.stream(points.get(1).split(",")).collect(Collectors.toList());

            List<String> rightDown = Arrays.asList(rightUp.get(0), leftDown.get(1));
            List<String> leftUp = Arrays.asList(leftDown.get(0), rightUp.get(1));
            points.clear();
            points.add(String.join(",", leftDown));
            points.add(String.join(",", rightDown));
            points.add(String.join(",", rightUp));
            points.add(String.join(",", leftUp));
            points.add(String.join(",", leftDown));
            System.out.println(points);
        }
        if (!StrUtil.equals(points.get(0), points.get(points.size() - 1))) {
            result.set("code", 500);
            result.set("message", "传入的经纬度不是一个闭合区域,最后一个点应该等于第一个点");
            return JSONUtil.toJsonStr(result);
        }
        // 查询区域内有多少禁飞区
        String polygon =  points.stream().map(s -> s.replace(",", " ")).collect(Collectors.joining(","));
        List<Area> allArea = areaService.intersects(polygon);
        // 组成树形结构
        List<Tree<Long>> trees = areaService.getTrees(allArea);
        result.set("data", trees);
        return JSONUtil.toJsonStr(result);
    }

    @DeleteMapping("{idPath}")
    public String delete(@PathVariable("idPath") String idPath) {
        JSONObject result = new JSONObject();
        result.set("code", 200);
        areaService.lambdaUpdate().likeRight(Area::getIdPath, idPath).remove();
        return JSONUtil.toJsonStr(result);
    }

    @PostMapping("")
    public String save(@RequestBody String body) {
        JSONObject result = new JSONObject();
        result.set("code", 200);

        Area areas = JSONUtil.toBean(body, Area.class);
        try {
            areaService.saveEntity(areas);
        } catch (Exception e) {
            result.set("code", 500);
            result.set("message", e.getMessage());
        }

        return JSONUtil.toJsonStr(result);
    }
}
